// Package ifaceutil 网络接口的函数
package ifaceutil

import (
	"bytes"
	"errors"
	"net"
)

// GetIfaceByIP 根据 IP 地址获取本机的指定的接口
func GetIfaceByIP(ip net.IP) (*net.Interface, error) {
	inters, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	for _, inter := range inters {
		addrs, err := inter.Addrs()
		if err != nil {
			return nil, err
		}

		for _, addr := range addrs {
			interIP, _, _ := net.ParseCIDR(addr.String())
			if interIP.Equal(ip) {
				return &inter, nil
			}
		}
	}
	return nil, errors.New("no related network interface")
}

// GetIfaceByMAC 根据 MAC 地址获取本机的指定的接口
func GetIfaceByMAC(mac net.HardwareAddr) (*net.Interface, error) {
	inters, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	for _, inter := range inters {
		if bytes.Equal(inter.HardwareAddr, mac) {
			return &inter, nil
		}
	}
	return nil, errors.New("no related network interface")
}
